package net.javaw.callplatform;

import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;

import net.javaw.callplatform.util.DialogUtil;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.ContactsContract;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


@SuppressLint({ "WorldReadableFiles", "NewApi" })
public class Notifications extends Activity {

	// 定义界面中两个文本框
	EditText Ecalled;
	// 定义界面中两个按钮
	Button Bcontacts, Bcall, Bcancel;

	SharedPreferences preferences;
	SharedPreferences.Editor editor;

	private String contactId, contactName, contactNumber;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		//2.2版本以前需注释
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
		 .detectDiskReads()
		 .detectDiskWrites()
		 .detectNetwork() // 这里可以替换为detectAll() 就包括了磁盘读写和网络I/O
		 .penaltyLog() //打印logcat
		 .build());
		 StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
		 .detectLeakedSqlLiteObjects() //探测SQLite数据库操作
		 .penaltyLog() //打印logcat
		 .penaltyDeath()
		 .build()); 
		 
		super.onCreate(savedInstanceState);
		setContentView(R.layout.notifications);

		// 获取只能被本应用程序读、写的SharedPreferences对象
		preferences = getSharedPreferences("net.javaw.callplatform", MODE_WORLD_READABLE);
		editor = preferences.edit();
		
		// 首次使用需先设置本机号码
		if (null == preferences.getString("caller", null)) {
			Toast.makeText(getApplicationContext(), "首次使用请先设置本机号码！\n\n步骤：\n\n1、选择菜单键，进入本机号码设置界面\n\n2、输入本机号码，保存", Toast.LENGTH_LONG).show();
		}

		Ecalled = (EditText) findViewById(R.id.called);
		
		if(null!=preferences.getString("called", null))
		{
			Ecalled.setText(preferences.getString("called", null));
		}

		Bcontacts = (Button) findViewById(R.id.contacts);
		Bcontacts.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), 0);
			}
		});

		Bcall = (Button) findViewById(R.id.call);
		Bcancel = (Button) findViewById(R.id.cancel);

		Bcancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
				// 删除注销标识
				editor.remove("logout");

				// 存入注销标识
				editor.putString("logout", "true");
				// 提交所有存入的数据
				editor.commit();

				// 启动Main Activity
				Intent intent = new Intent(Notifications.this, Login.class);
				startActivity(intent);
				// 结束该Activity
				finish();
			}
		});
		Bcall.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
				
				// 读取字符串数据
				String caller = preferences.getString("caller", null);

				if (null != caller&&!"".equals(caller)) {
					String called = Ecalled.getText().toString();
					
					if(null != called&&!"".equals(called)){
						// 删除旧的本机号码
						editor.remove("called");
						// 存入本机号码
						editor.putString("called", called);
						// 提交所有存入的数据
						editor.commit();
						
						try {

							notifications(caller, called);
							
							Toast.makeText(getApplicationContext(), "呼叫成功！\n\n请稍等。。。\n\n稍后会先接通主叫号码，\n\n再接通被叫号码", Toast.LENGTH_LONG).show();

						} catch (Exception e) {

							DialogUtil.showDialog(Notifications.this, "呼叫失败！ \n\n请重新呼叫", false);

							e.printStackTrace();
						}
					}else {
						Toast.makeText(getApplicationContext(), "被叫号码不能为空！\n\n请先从通讯录选择被叫号码\n\n或\n\n手动输入被叫号码", Toast.LENGTH_LONG).show();
					}

					
				} else {
					Toast.makeText(getApplicationContext(), "您尚未设置本机号码！\n\n请先设置本机号码\n\n步骤：\n\n1、选择菜单键，进入本机号码设置界面\n\n2、输入本机号码，保存", Toast.LENGTH_LONG).show();
				}

			}
		});

	}

	// 定义发送请求的方法
	private void notifications(String caller, String called) throws Exception {
		Socket socket = new Socket("221.176.200.58", 9998);

		OutputStream outputStream = socket.getOutputStream();

		OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);

		String str = new StringBuilder("4100#DROW#10086#" + caller + "#" + called + "&").toString();

		outputStreamWriter.write(str);

		outputStreamWriter.close();

		outputStream.close();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		super.onActivityResult(requestCode, resultCode, data);

			if (resultCode == Activity.RESULT_OK) {

				if (data == null) {

					Toast.makeText(getApplicationContext(), "读取联系人失败\n\n请手动输入联系人电话", Toast.LENGTH_LONG).show();

					return;
				}

				// ContentProvider展示数据类似一个单个数据库表
				// ContentResolver实例带的方法可实现找到指定的ContentProvider并获取到ContentProvider的数据
				ContentResolver reContentResolverol = getContentResolver();

				// URI,每个ContentProvider定义一个唯一的公开的URI,用于指定到它的数据集
				Uri contactData = data.getData();

				// 查询就是输入URI等参数,其中URI是必须的,其他是可选的,如果系统能找到URI对应的ContentProvider将返回一个Cursor对象.
				Cursor cursor = managedQuery(contactData, null, null, null, null);
				cursor.moveToFirst();

				// 获得DATA表中的名字
				contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

				// 条件为联系人ID
				contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));

				// 获得DATA表中的电话号码，条件为联系人ID,因为手机号码可能会有多个
				Cursor phone = reContentResolverol.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
				while (phone.moveToNext()) {
					contactNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
				}

				Ecalled = (EditText) findViewById(R.id.called);
				Ecalled.setText(contactNumber);

				Toast.makeText(getApplicationContext(), "读取联系人成功\n\n姓名：" + contactName + "\n\n联系方式 ：" + contactNumber, Toast.LENGTH_SHORT).show();

		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		Toast.makeText(getApplicationContext(), "待扩展。。。\n\n河南卓辉通信技术有限公司版权所有\n\n免责声明\n\n河南卓辉通信版权所有\n\n作者：史守阳\n\n仅限河南卓辉通信内部员工使用", Toast.LENGTH_LONG).show();
		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			// 获取只能被本应用程序读、写的SharedPreferences对象
			preferences = getSharedPreferences("net.javaw.callplatform", MODE_WORLD_READABLE);
			editor = preferences.edit();

			// 删除注销标识
			editor.remove("logout");

			// 存入注销标识
			editor.putString("logout", "true");
			// 提交所有存入的数据
			editor.commit();

			// 启动Main Activity
			Intent intent = new Intent(Notifications.this, Login.class);
			startActivity(intent);
			// 结束该Activity
			finish();

		} else if (keyCode == KeyEvent.KEYCODE_MENU) {
			Toast.makeText(getApplicationContext(), "设置本机号码\n\n步骤：\n\n1、选择菜单键，进入本机号码设置界面\n\n2、输入本机号码，保存", Toast.LENGTH_LONG).show();

			// 启动Main Activity
			Intent intent = new Intent(Notifications.this, Setting.class);
			startActivity(intent);
			// 结束该Activity
			finish();
		}
		return true;
	}

}
